package com.example.demo.demos.replaceKey;

import com.monitorjbl.xlsx.StreamingReader;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import static com.example.demo.DemoApplication.rootPath;


/**
 * 读取excel新旧字段到map
 * @Author: lixz
 * @Date: 2024/07/24/20:09
 */
//@Component
public class ReadExcel implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(ReadTypeJs.class);

    public final static Map<String, Object> excelKey = new HashMap<>();

    public static Long startTime = 0L;

    @Order(value = 1)
    @Override
    public void run(ApplicationArguments args){
        startTime = System.nanoTime();
        try {
            File[] files = new File(rootPath).listFiles();
            assert files != null;
            for (File file : files) {
                String name = file.getName();
                if (! name.endsWith(".xlsx")) {
                    continue;
                }
                getInputStream(file);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        long endTime = System.nanoTime();
        long seconds = TimeUnit.NANOSECONDS.toSeconds(endTime-startTime);
        log.info("读取写入excel key总时间:{}",seconds);
    }

    static void getInputStream(File file) throws IOException {
        InputStream is = Files.newInputStream(Paths.get(file.getCanonicalPath()));

        Workbook workbook = StreamingReader.builder()
                .bufferSize(4096) // 设置缓存的大小
                .rowCacheSize(500) // 缓存行的数量，也就是每次读取多少行到内存中，而不是一下子全都加载进内存
                .open(is); // 设置要打开的文件
//        Workbook workbook = WorkbookFactory.create(is);
        Sheet sheetAt = workbook.getSheetAt(1);
        for (Row row : sheetAt) {
            if (row == null) {
                continue;
            }
            String oldKey = row.getCell(4).getStringCellValue();
            if (!excelKey.containsKey(oldKey)) {
                String newKey = row.getCell(28).getStringCellValue();
                excelKey.put(oldKey, newKey);
            }
        }
    }

}
